package com.auto.learning.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.BreakPointBean;
import com.auto.learning.bean.PlayBean;
import com.auto.learning.bean.PlayChangeEvent;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SelectionVo;
import com.auto.learning.event.BookNumChangeEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.PlayTypeEvent;
import com.auto.learning.event.RefreshPlayListEvent;
import com.auto.learning.net.Cache;
import com.auto.learning.net.DownLoadInfo;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.receiver.HeadSetHelper;
import com.auto.learning.receiver.HeadSetHelper.OnHeadSetListener;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FileUtil;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.SharedPreferencesUtils;

/**
 * 管理播放列表
 * 
 * @author wangjianjun
 */
public class MusicPlayManager implements IPlayOperate, AMapLocationListener {

	private AMapLocation startLocation = null;
	private AMapLocation endLocation = null;

	private static final int CHAPTER_PROFESSIONAL = 1;
	private static final int CHAPTER_DOUBI = 2;
	private static final int CHAPTER_ENGLISH = 3;

	private Context context;
	private ArrayList<BookBean> playList = new ArrayList<BookBean>();
	private int bookPosition = 0;
	private int chapterPosition = 0;
	private static MusicPlayManager musicPlayManager;

	private int bookId;
	private int chapterId = -1;
	private boolean isPlaying;

	private boolean continueFlag = false;
	private boolean needContinue = false; // 是否考虑断点

	private boolean continuePlayPause = false; // 此值得意思是
												// 刚打开界面时候，未播放，此时是断点作品，需要暂停，默认为false

	private int playType = 0; // 0:专业，1:逗比，2:英文

	private int seekTo = 0;

	private boolean playFinished = false; // 标识是否已经是最后一个章节并且已经播放完毕了

	private Handle handle = new Handle(context) {
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.SEND_LISTEN_STATUS_SUCCESS:
				startLocation = null;
				ResponeResult result = (ResponeResult) msg.obj;
				try {
					if (result != null) {
						JSONObject jsonObject = new JSONObject(result.getData());
						int isChange = jsonObject.getInt(HttpRequestHelper.BOOKNUM_ISCHANGED); // 1否2是
						int bookNum = jsonObject.getInt("bookNum");
						int userId = (int) SharedPreferencesUtils.getParam(context, HttpRequestHelper.USERID, 0);
						if (isChange == 2) {
							SharedPreferencesUtils.setParam(context,userId+ "_"+ HttpRequestHelper.BOOKNUM_ISCHANGED,isChange);
							EventBus.getEventBus("readbook_num_change").post(new BookNumChangeEvent(bookNum, msg.arg1));
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			case HttpRequestHelper.SEND_LISTEN_STATUS_FAIL:

				break;
			}
		};
	};

	public MusicPlayManager(Context context, ArrayList<BookBean> playList) {
		this.context = context;
		this.playList = playList;
	}

	public MusicPlayManager(Context context) {
		this.context = context;
		initBlueTooth(context);
	}

	public static MusicPlayManager getInstance(Context context) {
		if (musicPlayManager == null) {
			musicPlayManager = new MusicPlayManager(context);
		}
		return musicPlayManager;
	}

	public MusicPlayManager setPlayList(ArrayList<BookBean> playList) {
		this.needContinue = true;
		this.playList = playList;
		return this;
	}

	public MusicPlayManager setBookPosition(int bookPosition) {
		this.bookPosition = bookPosition;
		getBreakPointData();
		return this;
	}

	public MusicPlayManager setChapterPosition(int chapterPosition) {
		this.chapterPosition = chapterPosition;
		return this;
	}

	public MusicPlayManager setBookId(int bookId) {
		return setBookAndChapterIds(bookId, -1);
	}

	public MusicPlayManager setChapterId(int chapterId) {
		return setBookAndChapterIds(bookId, chapterId);
	}

	public MusicPlayManager setBookAndChapterIds(int bookId, int chapterId) {
		this.bookId = bookId;
		this.chapterId = chapterId;
		getBreakPointData();
		return this;
	}

	/**
	 * 获取断点播放的位置
	 */
	public void getBreakPointData() {
		int c_booKId = 0;
		int c_chapterId = 0;
		try {
			BreakPointBean breakPointBean = TemporaryVariable.breakPiontMap.get(bookId);
			if (breakPointBean != null) {
				c_booKId = breakPointBean.getBookId();
				c_chapterId = breakPointBean.getChapterId();
			} else {
				c_booKId = (int) SharedPreferencesUtils.getParam(context,HttpRequestHelper.CONTINUE_PLAY_BOOKID, 0);
				c_chapterId = (int) SharedPreferencesUtils.getParam(context,HttpRequestHelper.CONTINUE_PLAY_CHAPTERID, 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			c_booKId = (int) SharedPreferencesUtils.getParam(context,HttpRequestHelper.CONTINUE_PLAY_BOOKID, 0);
			c_chapterId = (int) SharedPreferencesUtils.getParam(context,HttpRequestHelper.CONTINUE_PLAY_CHAPTERID, 0);
		}
		initPosition(c_booKId, c_chapterId);
	}
	
	/**
	 * 退出登录时刷新播放列表
	 * @param c_booKId
	 * @param c_chapterId
	 */
	public void refreshPlayList(){
		int[] ids = isPlayingBookId();
		if (playList != null && playList.size() > 0) {
			for (int i = 0; i < playList.size(); i++) {
				if (!TemporaryVariable.downLoadedList.contains(playList.get(i).getBookId()) && playList.get(i).getFree() != 2) {
					if (playList.get(i).getBookId() != ids[0]) {
						playList.remove(i);
						i--;
					}
				}
			}
			initPosition(ids[0], ids[1]);
		}
	}

	/**
	 * 初始化当前要播放的作品在列表中的位置 bookPosition --书的位置 chapterId -- 书中章节的位置
	 */
	public void initPosition(int c_booKId, int c_chapterId) {
		if (playList != null && playList.size() > 0) {
			for (BookBean item : playList) {
				if (item.getBookId() == bookId) {
					bookPosition = playList.indexOf(item);
					bookId = item.getBookId();
					if (chapterId == -1) {
						chapterPosition = 0;
						if (item.getSectionList() != null && item.getSectionList().size() > 0) {
							this.chapterId = item.getSectionList().get(0).getSectionId();
						}
					} else {
						for (SelectionVo vo : item.getSectionList()) {
							if (chapterId == vo.getSectionId()) {
								chapterPosition = item.getSectionList().indexOf(vo);
								chapterId = vo.getSectionId();
								break;
							}
						}
					}
					if (needContinue && (boolean) SharedPreferencesUtils.getParam(context, HttpRequestHelper.CONTINUE_PLAY_BEFORE, true)) {
						needContinue = false;
						if (bookId == c_booKId) {
							BreakPointBean temp_breakPoint = TemporaryVariable.breakPiontMap.get(bookId);
							if (temp_breakPoint != null) {
								seekTo = temp_breakPoint.getSeekTo();
							} else {
								seekTo = 0;
							}
							for (SelectionVo vo : item.getSectionList()) {
								if (c_chapterId == vo.getSectionId()) {
									chapterPosition = item.getSectionList().indexOf(vo);
									chapterId = vo.getSectionId();
									break;
								}
							}
						}
					}
					break;
				}
			}
		}
		Log.d("M_position", "bookPosition :" + bookPosition + ", chapterPosition :" + chapterPosition);
	}

	/**
	 * 正在播放的bean ID
	 */
	public int[] isPlayingBookId() {
		int playingIds[] = new int[3];
		if (playList != null && playList.size() > 0) {
			BookBean bean = playList.get(bookPosition);
			playingIds[0] = bean.getBookId();
			if (bean.getSectionList() != null && bean.getSectionList().size() > chapterPosition) {
				playingIds[1] = bean.getSectionList().get(chapterPosition).getSectionId();
			} else {
				playingIds[1] = 0;
			}
		} else {
			playingIds[0] = 0;
			playingIds[1] = 0;
		}
		playingIds[2] = isPlaying ? 0 : 1;
		return playingIds;
	}

	/**
	 * 获取图片列表
	 * 
	 * @return
	 */
	public String getFaceImage() {
		String imgUrl = "";
		if (playList != null && playList.size() > 0) {
			imgUrl = playList.get(bookPosition).getFaceImg();
		}
		return imgUrl;
	}

	public int getCanRead() {
		int canRead = 2;
		if (playList != null && playList.size() > 0) {
			canRead = playList.get(bookPosition).getCanRead();
		}
		return canRead;
	}

	@Override
	public void play() {
		if (playList != null && playList.size() == 0) {
			return;
		}
		if (playList.size() - 1 < bookPosition) {
			bookPosition = 0;
			return;
		}
		List<SelectionVo> selectionVos = playList.get(bookPosition).getSectionList();
		if (selectionVos == null || (selectionVos != null && selectionVos.size() == 0)) {
			return;
		}
		
		PlayBean playBean = new PlayBean();
		int type = (int) SharedPreferencesUtils.getParam(context,"chapter_type", CHAPTER_PROFESSIONAL);
		SelectionVo selectionVo = selectionVos.get(chapterPosition);
		int bId = playList.get(bookPosition).getBookId();
		switch (type) {
		case CHAPTER_PROFESSIONAL:
			if (selectionVo.getProSec() == 0) {
				if (!checkType(CHAPTER_PROFESSIONAL, selectionVo)) {
					play();
				}
				return;
			}
			playBean.setPlayUrl(selectionVo.getProAudioUrl());
			break;
		case CHAPTER_DOUBI:
			if (selectionVo.getDoubiSec() == 0) {
				if (!checkType(CHAPTER_DOUBI, selectionVo)) {
					play();
				}
				return;
			}
			playBean.setPlayUrl(selectionVo.getDoubiAudioUrl());
			break;
		case CHAPTER_ENGLISH:
			if (selectionVo.getEnSec() == 0) {
				if (!checkType(CHAPTER_ENGLISH, selectionVo)) {
					play();
				}
				return;
			}
			playBean.setPlayUrl(selectionVo.getEnAudioUrl());
			break;
		}

		if (playBean == null || (playBean != null && TextUtils.isEmpty(playBean.getPlayUrl()))) {
			next();
		}
		if (TemporaryVariable.downLoadedList.contains(bId)) {
			String fileName = CommonMethod.getFileName(playBean.getPlayUrl());
			String filePath = FileUtil.getFileCachePath() + DownLoadInfo.DOWNLOAD + "/" + bId + "/" + fileName;
			File file = new File(filePath);
			if (file.exists()) {
				playBean.setPlayUrl(filePath);
			}
		}

		// 每次播放前保存断点位置
		SharedPreferencesUtils.setParam(context,HttpRequestHelper.CONTINUE_PLAY_BOOKID, bId);
		SharedPreferencesUtils.setParam(context,HttpRequestHelper.CONTINUE_PLAY_CHAPTERID, selectionVo.getSectionId());
		Cache.setPlayCacheContinueBook(playList.get(bookPosition));
		if (seekTo > 0) {
			playBean.setSeekTo(seekTo);
			seekTo = 0;
		}
		playBean.setContinuePlayPause(continuePlayPause);
		if (continuePlayPause)
			continuePlayPause = false;
		try {
			playBean.setLast(playList.size() - 1 == bookPosition && playList.get(bookPosition).getSectionList().size() - 1 == chapterPosition);
		} catch (Exception e) {
			e.printStackTrace();
		}
		EventBus.getEventBus("m_play").post(playBean);
		if (playList != null && playList.size() > 0) {
			EventBus.getEventBus("m_play_bookbean_change").post(new PlayChangeEvent(bId));
			EventBus.getEventBus("current_play_Type").post(new PlayTypeEvent(type));
			EventBus.getEventBus("refresh_PlayList").post(new RefreshPlayListEvent());
		}
	}

	@Override
	public void next() {
		if (playList == null && playList.size() > 0) {
			return;
		}
		sendListenStatus();
		if (playList.get(bookPosition).getSectionList().size() - 1 > chapterPosition) { // 下一个章节
			chapterPosition++;
			if (checkHasChapter()) {
				next();
				return;
			} else {
				play();
			}
		} else if (playList.size() - 1 > bookPosition) { // 下一本书
			TemporaryVariable.breakPiontMap.remove(isPlayingBookId()[0]);
			bookPosition++;
			chapterPosition = 0;
			showNetTips = true;
			play();
		} else {
			TemporaryVariable.breakPiontMap.remove(isPlayingBookId()[0]); // 移除已经读完所有书
			CommonMethod.makeNotice(context, "最后一本书啦！");
		}
		CommonMethod.recordBreakPoint();
		Log.d("M_position", "bookPosition :" + bookPosition + ", chapterPosition :" + chapterPosition);
	}

	/**
	 * 是否要显示提示信息
	 */
	private boolean showNetTips = false; // 网络切换时

	// private boolean hasPlayLittle = true; //
	// 已经播放了，但是在移动网络环境点了提示框的取消按钮，此后还需要提示的

	public boolean needCheckNet() {
		return showNetTips&& !(boolean) SharedPreferencesUtils.getParam(context,HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)&& CommonMethod.getNetworkState(context) == 2&& !TemporaryVariable.downLoadedList.contains(isPlayingBookId()[0])&& !HttpCommonInfo.M_NET_DIALOG_SHOW;
	}

	public boolean getShowNetTips() {
		return showNetTips;
	}

	public void setShowNetTips(boolean b) {
		this.showNetTips = b;
	}

	public boolean checkHasChapter() {
		boolean mFlag = false;
		if (playList != null && playList.size() > 0) {
			int type = (int) SharedPreferencesUtils.getParam(context,"chapter_type", 1);
			SelectionVo vo = playList.get(bookPosition).getSectionList().get(chapterPosition);
			switch (type) {
			case 1:
				if (vo.getProSec() == 0) {
					mFlag = true;
				}
				break;
			case 2:
				if (vo.getDoubiSec() == 0) {
					mFlag = true;
				}
				break;
			case 3:
				if (vo.getEnSec() == 0) {
					mFlag = true;
				}
				break;
			}
		}
		return mFlag;
	}

	@Override
	public void previous() {
		if (playList == null && playList.size() > 0) {
			return;
		}
		sendListenStatus();
		if (chapterPosition > 0) {
			chapterPosition--;
			if (checkHasChapter()) {
				previous();
				return;
			} else {
				play();
			}
		} else if (bookPosition > 0) {
			bookPosition--;
			// chapterPosition = playList.get(bookPosition).getSectionList().size() - 1;
			chapterPosition = 0;
			play();
		} else {
			CommonMethod.makeNotice(context, "已经是第一本啦！");
		}
		Log.d("M_position", "bookPosition :" + bookPosition + ", chapterPosition :" + chapterPosition);
	}

	@Override
	public void pause() {
		if (playList != null && playList.size() > 0) {
			if (playFinished) {
				chapterPosition = 0;
				playFinished = false;
				play();
			} else {
				EventBus.getEventBus("m_pause").post(isPlaying);
			}
		}
	}

	public boolean isPlaying() {
		return isPlaying;
	}

	public void setPlaying(boolean isPlaying) {
		this.isPlaying = isPlaying;
	}

	public ArrayList<BookBean> getPlayList() {
		return this.playList;
	}

	public boolean isContinuePlayPause() {
		return continuePlayPause;
	}

	public MusicPlayManager setContinuePlayPause(boolean continuePlayPause) {
		this.continuePlayPause = continuePlayPause;
		return this;
	}

	public int getPlayType() {
		return playType;
	}

	public void setPlayType(int playType) {
		this.playType = playType;
	}

	public boolean isNeedContinue() {
		return needContinue;
	}

	public MusicPlayManager setNeedContinue(boolean needContinue) {
		this.needContinue = needContinue;
		return this;
	}

	@Override
	public void onLocationChanged(Location location) {

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	@Override
	public void onProviderEnabled(String provider) {

	}

	@Override
	public void onProviderDisabled(String provider) {

	}

	@Override
	public void onLocationChanged(AMapLocation mapLocation) {
		// Log.d("AMapLocation", mapLocation.getLatitude()+"," +
		// mapLocation.getLongitude());
		if (startLocation == null) {
			startLocation = mapLocation;
		}
		endLocation = mapLocation;
	}

	private void sendListenStatus() {
		if (playList == null || (playList != null && playList.size() == 0)) {
			return;
		}
		int listenTime = 0;
		int type = (int) SharedPreferencesUtils.getParam(context, "chapter_type", CHAPTER_PROFESSIONAL);
		SelectionVo selectionVo = playList.get(bookPosition).getSectionList().get(chapterPosition);
		int bId = playList.get(bookPosition).getBookId();
		switch (type) {
		case CHAPTER_PROFESSIONAL:
			listenTime = selectionVo.getProSec();
			break;
		case CHAPTER_DOUBI:
			listenTime = selectionVo.getDoubiSec();
			break;
		case CHAPTER_ENGLISH:
			listenTime = selectionVo.getEnSec();
			break;
		}
		try {
			if (playList.size() - 1 == bookPosition
					&& playList.get(bookPosition).getSectionList().size() - 1 == chapterPosition) {
				playFinished = true;
			} else {
				playFinished = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			playFinished = false;
		}
		HttpRequestHelper.sendListenStatue(context, handle, bId, selectionVo.getSectionId(), startLocation, endLocation,listenTime);
	}

	/**
	 * 检查是否存在此播音
	 * 
	 * @param chapter
	 */
	public boolean checkType(int chapter_type, SelectionVo vo) {
		int type = -1;
		if (vo != null) {
			switch (chapter_type) {
			case 1:
				type = vo.getProSec() > 0 ? 1 : -1;
				break;
			case 2:
				type = vo.getDoubiSec() > 0 ? 2 : -1;
				break;
			case 3:
				type = vo.getEnSec() > 0 ? 3 : -1;
				break;
			default:
				type = -1;
				break;
			}
			if (type == -1) { // 不存在
				if (vo.getProSec() > 0) {
					type = 1;
				} else if (vo.getDoubiSec() > 0) {
					type = 2;
				} else if (vo.getEnSec() > 0) {
					type = 3;
				}
			}
			SharedPreferencesUtils.setParam(context, "chapter_type", type);
			EventBus.getEventBus("refresh_PlayList").post(new RefreshPlayListEvent());
		}
		return type == chapter_type;
	}

	/**
	 * 获取正在播放的书
	 */
	public BookBean getCurrentPlayingBookBean() {
		BookBean bookBean = null;
		if (playList != null && playList.size() > 0) {
			if (bookPosition <= playList.size() - 1) {
				bookBean = playList.get(bookPosition);
			}
		}
		return bookBean;
	}

	/**
	 * 初始化蓝牙模块
	 */
	private void initBlueTooth(Context context) {
		HeadSetHelper.getInstance().setOnHeadSetListener(headSetListener);
		HeadSetHelper.getInstance().open(context);
	}

	/**
	 * 蓝牙相关
	 */
	OnHeadSetListener headSetListener = new OnHeadSetListener() {

		@Override
		public void playPreview() {
			previous();
		}

		@Override
		public void playNext() {
			next();
		}

		@Override
		public void musicPlayOrpause() {
			pause();
		}

		@Override
		public void onClick() {
			pause();
		}

		@Override
		public void onDoubleClick() {
			next();
		}
	};

}
